using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Pay.DTO;
using Pay.IService;
using Pay.Data;
using Pay.Service.Cache;
using Pay.TO;
using Pay.Core;

namespace Pay.Service {
	public class BulletinService : ServiceBase, IBulletinService, IDisposable {
		private IUnitOfWork _iUnitOfWork;

		public BulletinService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
			_iUnitOfWork = iUnitOfWork;
		}

		public PagedResult<bulletin_dto> Get(string name, int page, int rows) {
			Expression<Func<Bulletin, bool>> filter = c => true;
			if (!string.IsNullOrEmpty(name))
				filter = filter.And(c => c.Title.Contains(name));
			return context.Bulletins.FromCachePaged<Bulletin, bulletin_dto>(page, rows, filter, orderBy => orderBy.OrderByDescending(c => c.Id), "Bulletin");
		}

		public bulletin_dto Get(long id) {
			var query = context.Bulletins.Where(c => c.Id == id);
			return query.FromCacheFirstOrDefault<Bulletin, bulletin_dto>("Bulletin");
		}
		/// <summary>
		/// 新增公告不可以发送
		/// </summary>
		/// <param name="dto"></param>
		/// <returns></returns>
		public int Insert(bulletin_dto dto) {
			context.Bulletins.Add(dto.ToDtoObject<Bulletin>());
			int result = _iUnitOfWork.Commit("Bulletin");
			return result;
		}

		public int Update(bulletin_dto dto) {
			var model = context.Bulletins.FindById(dto.id);
			dto.ToDtoObject(model);
			var tags = new List<string>();
			tags.Add("Bulletin");
			if (dto.send_by == 1 && dto.status == 1) {
				List<Merchant> users = new List<Merchant>();
				if (string.IsNullOrEmpty(dto.mobile)) {
					var user = context.Merchants.FirstOrDefault(c => c.Mobile == dto.mobile && c.Disabled == false);
					users.Add(user);
				} else
					users = context.Merchants.Where(c => c.Disabled == false).ToList();
				users.ForEach(user => {
					context.MessagePushs.Add(new MessagePush {
						CreateTime = DateTime.Now.ToUnix(), ObjectId = dto.id, Type = MsgType.Bulletin, MerchantId = user.Id,
						ShortContent = dto.short_content, Content = dto.content, Title = dto.title, ImagePath = dto.image_path
					});
					tags.Add("MessagePush" + user.Id);
				});
				model.Status = 2;
			}
			int result = _iUnitOfWork.Commit(tags.ToArray());
			return result;
		}

		public int Delete(List<long> ids) {
			foreach (var id in ids)
				context.Bulletins.Remove(id);
			int result = _iUnitOfWork.Commit("Bulletin");
			return result;
		}
	}
}
